import React, { useState } from 'react';
import { Card, Form, Input, Button, message, DatePicker, Radio, Select } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { userpageadd } from '@/services/system/user';
import { createStyles } from 'antd-style';
import moment from 'moment';
import { PageContainer } from '@ant-design/pro-components';
import {  getDepartmentList, getPositionList } from '@/services/ant-design-pro/api';
import { useModel } from 'umi';
import { Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import CustomPageContainer from '@/components/CustomPageContainer';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    margin: '0 auto',
  },

  formContainer: {
    maxWidth: '800px',
    width: '100%',
    margin: '0 auto',
    padding: '32px',
    background: '#fff',
    borderRadius: '8px',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  formItem: {
    marginBottom: '24px',
    '& .ant-form-item-label': {
      fontWeight: 500,
      color: '#333',
    },
    '& .ant-input': {
      borderRadius: '4px',
      '&:focus': {
        borderColor: '#1890ff',
        boxShadow: '0 0 0 2px rgba(24, 144, 255, 0.2)',
      },
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

const UserManageAdd: React.FC = () => {
  const { institutionId, institutionRoleId } = useModel('auth');
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [departmentOptions, setDepartmentOptions] = useState<any[]>([]);
  const [fetchingDepartments, setFetchingDepartments] = useState(false);
  const [positionOptions, setPositionOptions] = useState<any[]>([]);
  const [fetchingPositions, setFetchingPositions] = useState(false);

  // 获取部门列表
  const fetchDepartments = async () => {
    if (!institutionId || !institutionRoleId) return;

    setFetchingDepartments(true);
    try {
      const response = await getDepartmentList({
        institutionId,
        institutionRoleId
      });

      if (response.code === 200 && response.data) {
        const options = response.data.map((item: any) => ({
          value: item.departmentId,
          label: item.deptName
        }));
        setDepartmentOptions(options);
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
    } finally {
      setFetchingDepartments(false);
    }
  };

  // 获取岗位列表
  const fetchPositions = async () => {
    const departmentId = form.getFieldValue('department');
    if (!institutionId || !institutionRoleId || !departmentId) return;

    setFetchingPositions(true);
    try {
      const response = await getPositionList({
        institutionId,
        institutionRoleId,
        departmentId
      });

      if (response.code === 200 && response.data) {
        const options = response.data.map((item: any) => ({
          value: item.positionId,
          label: item.positionName
        }));
        setPositionOptions(options);
      }
    } catch (error) {
      console.error('获取岗位列表失败:', error);
      message.error('获取岗位列表失败');
    } finally {
      setFetchingPositions(false);
    }
  };

  const onFinish = async (values: any) => {
    console.log('提交的值:', values);

    setLoading(true);
    try {
      const formData = {
        ...values,
        departmentId: values.department,  // 确保部门ID字段正确
        positionId: values.position,      // 确保岗位ID字段正确
        birthday: values.birthday ? moment(values.birthday).format('YYYY-MM-DD') : undefined,
        phone: values.phone || '1.77E+10',
        status: values.status === '启用' ? 0 : 1,
        institutionId: institutionId,
      };

      console.log('最终提交的数据:', formData);  // 调试用，查看最终提交的数据结构

      const response = await userpageadd(formData);

      if (response.code === 200) {
        message.success('提交成功');
        navigate('/system/usermanage');
      } else {
        message.error(response.msg || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 证件类型选项
  const cardTypeOptions = [
    { value: '1', label: '身份证' },
    { value: '2', label: '护照' },
    { value: '3', label: '驾驶证' },
  ];

  return (
    <CustomPageContainer>
      <Card>
        <div className={styles.formContainer}>
          <div className={styles.title}>用户详情</div>
          <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item
              label="用户名"
              name="userName"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>

            <Form.Item
              label="姓名"
              name="name"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>

            <Form.Item
              label="密码"
              name="userPassword"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>

            <Form.Item
              label="性别"
              name="sex"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择性别' }]}
            >
              <Radio.Group>
                <Radio value={0}>男</Radio>
                <Radio value={1}>女</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              label="生日"
              name="birthday"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择生日' }]}
            >
              <DatePicker
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
              />
            </Form.Item>

            <Form.Item
              label="地址"
              name="address"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入地址' }]}
            >
              <Input placeholder="请输入地址" />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phone"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入手机号' }]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              label="电子邮箱"
              name="email"
              className={styles.formItem}
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>

            <Form.Item
              label="证件类型"
              name="cardType"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择证件类型' }]}
            >
              <Select
                placeholder="请选择证件类型"
                options={cardTypeOptions}
              />
            </Form.Item>

            <Form.Item
              label="证件号码"
              name="cardNumber"
              className={styles.formItem}
              rules={[{ required: true, message: '请输入证件号码' }]}
            >
              <Input placeholder="请输入证件号码" />
            </Form.Item>

            {/* <Form.Item
              label="证件照正面"
              name="cardFront"
              className={styles.formItem}
              rules={[{ required: true, message: '请上传证件照正面' }]}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                listType="picture"
                maxCount={1}
                beforeUpload={() => false} // 阻止自动上传
              >
                <Button icon={<UploadOutlined />}>上传正面照片</Button>
              </Upload>
            </Form.Item>

            <Form.Item
              label="证件照反面"
              name="cardBehind"
              className={styles.formItem}
              rules={[{ required: true, message: '请上传证件照反面' }]}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                listType="picture"
                maxCount={1}
                beforeUpload={() => false} // 阻止自动上传
              >
                <Button icon={<UploadOutlined />}>上传反面照片</Button>
              </Upload>
            </Form.Item> */}

            <Form.Item
              label="账号状态"
              name="status"
              className={styles.formItem}
              initialValue="启用"
            >
              <Radio.Group>
                <Radio value="启用">启用</Radio>
                <Radio value="禁用">禁用</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="部门"
              name="department"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择部门' }]}
            >
              <Select
                placeholder="请选择部门"
                options={departmentOptions}
                loading={fetchingDepartments}
                onFocus={fetchDepartments}
                showSearch
                optionFilterProp="label"
              />
            </Form.Item>

            <Form.Item
              label="岗位"
              name="position"
              className={styles.formItem}
              rules={[{ required: true, message: '请选择岗位' }]}
            >
              <Select
                placeholder="请选择岗位"
                options={positionOptions}
                loading={fetchingPositions}
                onFocus={fetchPositions}
                showSearch
                optionFilterProp="label"
              />
            </Form.Item>

            <div className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => navigate('/system/usermanage')}
              >
                返回
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                className={styles.button}
              >
                确定
              </Button>
            </div>
          </Form>
        </div>
      </Card>
    </CustomPageContainer>
  );
};

export default UserManageAdd;

